import logging

from django.shortcuts import render

# Create your views here.
from django.http import JsonResponse, HttpResponse
from rent.utils.commonConfig import (returnOriginJson, articleClass, tokenTag)
from mitmproxyModel.models import autoUploadedAPI
import json, requests
from mitmproxyModel.TrafficReplay.trafficRequest import ReplayApi


def upload(request):
    if request.method == 'GET':
        return JsonResponse(returnOriginJson, safe=False)
    elif request.method == 'POST':
        results = dict(returnOriginJson)
        results['info'] = str(" run crontab OK!")
        return JsonResponse(results, safe=False)


def uploadAPI(request):
    if request.method == "GET":
        return JsonResponse(returnOriginJson, safe=False)
    elif request.method == "POST":
        formData = json.loads(request.body)
        print(formData)
        data = formData.get('ReqReferer', 'test')
        print(data)
        try:
            apiObj = autoUploadedAPI.objects.create(
                reqHost=formData.get('reqHost', ''),
                reqPort=formData.get('reqPort', ''),
                reqScheme=formData.get('reqScheme', ''),
                reqHeaderCntentType=formData.get('reqHeaderCntentType', ''),
                ReqReferer=formData.get('ReqReferer', ''),
                reqPath=formData.get('reqPath', ''),
                reqUrl=formData.get('reqUrl', ''),
                reqMethod=formData.get('reqMethod', ''),
                reqQuery=formData.get('reqQuery', ''),
                reqContent=formData.get('reqContent', ''),
                reqUrlencodedForm=formData.get('reqUrlencodedForm', ''),
                reqMultipartForm=formData.get('reqMultipartForm', ''),
                reqPathComponents=formData.get('reqPathComponents', ''),
                # resHeader=formData.get('resHeader', ''),
                # text=formData.get('text', ''),
                # resData=formData.get('resData', ''),
                statusCode=formData.get('statusCode', ''),
                reason=formData.get('reason', ''),
                json=formData.get('json', ''),

            )
            apiObj.save()
        except Exception as error:
            print(error)
        results = dict(returnOriginJson)
        results['info'] = str("Successly uploaded api by mitmproxy!")
        return JsonResponse(results, safe=False)


def runRequestFromApi(request):
    if request.method == "GET":
        return JsonResponse(returnOriginJson, safe=False)
    elif request.method == "POST":
        try:
            apiId = int(json.loads(request.body).get('id'))
            replyObj = ReplayApi(id=apiId).getApidata()
            results = dict(returnOriginJson)
            results['info'] = replyObj
            return JsonResponse(results, safe=False)
        except Exception as error:
            print(error)
            logging.ERROR(error)
